// 导入对象存储工具函数
const { getObjectURL, getKeyFromURL, getDefaultAvatarURL } = require('../../utils/storage');

Page({
  data: {
    activeTab: 0,
    tabs: ['动态', '作品', '实践', '活动', '收藏'],
    // 轮播图数据
    bannerList: [
      { imageUrl: 'https://objectstorageapi.bja.sealos.run/a0qepsyj-001/miniprogram-cdn/banner1.png', title: 'JAVA大赛火热报名中' },
      { imageUrl: 'https://objectstorageapi.bja.sealos.run/a0qepsyj-001/miniprogram-cdn/banner2.png', title: '最新实践活动' },
      { imageUrl: 'https://objectstorageapi.bja.sealos.run/a0qepsyj-001/miniprogram-cdn/banner3.png', title: '优秀作品展示' }
    ],
    // 卡片列表数据
    cardList: [
      { 
        id: 1, 
        title: '张三', 
        avatar: 'https://objectstorageapi.bja.sealos.run/a0qepsyj-001/text/Default%20avatar/d907281-0.png', 
        views: 32, 
        groups: 3, 
        content: '这是我的第一条动态内容',
        collectCount: 15,
        commentCount: 8,
        shareCount: 5,
        watchCount: 32,
        isCollected: false,
        isWatched: false,
        publishTime: '10分钟前',
        relatedContent: {
          type: '岗位',
          title: '前端开发工程师',
          desc: '负责公司产品的前端开发，要求熟悉HTML、CSS、JavaScript等技术',
          coverUrl: 'https://objectstorageapi.bja.sealos.run/a0qepsyj-001/miniprogram-cdn/job-cover.png'
        },
        group: {
          name: '前端开发交流群',
          avatar: 'https://objectstorageapi.bja.sealos.run/a0qepsyj-001/miniprogram-cdn/group-avatar.png'
        },
        tags: ['前端开发', 'JavaScript', 'Vue.js']
      },
      { 
        id: 2, 
        title: '李四', 
        avatar: 'https://objectstorageapi.bja.sealos.run/a0qepsyj-001/text/Default%20avatar/d907281-1.png', 
        views: 45, 
        content: '分享今日学习心得',
        collectCount: 0,
        commentCount: 3,
        shareCount: 0,
        watchCount: 45,
        isCollected: false,
        isWatched: false,
        publishTime: '1小时前',
        relatedContent: {
          type: '活动',
          title: '校园招聘会',
          desc: '本周五在学校体育馆举行大型校园招聘会，有多家知名企业参与',
          coverUrl: 'https://objectstorageapi.bja.sealos.run/a0qepsyj-001/miniprogram-cdn/event-cover.png'
        },
        group: {
          name: '校园招聘交流群',
          avatar: 'https://objectstorageapi.bja.sealos.run/a0qepsyj-001/miniprogram-cdn/group-avatar2.png'
        },
        tags: ['校园招聘', '求职经验']
      },
      { 
        id: 3, 
        title: '王五', 
        avatar: 'https://objectstorageapi.bja.sealos.run/a0qepsyj-001/text/Default%20avatar/d928162-0.png', 
        views: 28,  
        content: 'JAVA比赛是由腾讯的音乐大赛主办...',
        collectCount: 6,
        commentCount: 0,
        shareCount: 2,
        watchCount: 28,
        isCollected: false,
        isWatched: false,
        publishTime: '今天 10:30',
        relatedContent: {
          type: '比赛',
          title: 'JAVA编程大赛',
          desc: '由腾讯音乐主办的全国高校JAVA编程挑战赛，奖金丰厚',
          coverUrl: 'https://objectstorageapi.bja.sealos.run/a0qepsyj-001/miniprogram-cdn/competition-cover.png'
        }
      },
      { 
        id: 4, 
        title: '赵六', 
        avatar: 'https://objectstorageapi.bja.sealos.run/a0qepsyj-001/text/Default%20avatar/d928162-1.png', 
        views: 36,  
        content: '今日参加了编程实践活动',
        collectCount: 20,
        commentCount: 12,
        shareCount: 8,
        watchCount: 36,
        isCollected: false,
        isWatched: false
      }
    ],
    // 评论相关数据
    showCommentPopup: false,
    currentCardIndex: -1,
    commentList: [],
    commentText: '',
    inputFocus: false,
    scrollIntoView: '',
    // 评论互动功能
    showCommentMenu: false,
    currentCommentIndex: -1,
    isOwnComment: false,
    replyTo: null,
    replyPlaceholder: ''
  },

  // 切换顶部标签
  switchTab: function (e) {
    const index = e.currentTarget.dataset.index;
    this.setData({ activeTab: index });
    console.log('切换到标签:', this.data.tabs[index]);
  },

  // 跳转到详情页
  navigateToDetail: function(e) {
    const id = e.currentTarget.dataset.id;
    console.log('正在跳转到帖子详情页，ID:', id);
    wx.navigateTo({
      url: '/pages/post-detail/post-detail?id=' + id,
      success: function() {
        console.log('跳转成功');
      },
      fail: function(err) {
        console.error('跳转失败:', err);
      }
    });
  },

  // 中间 + 号按钮点击
  handleCenterButton: function () {
    wx.showActionSheet({
      itemList: ['发布动态', '创建活动', '上传作品'],
      success: (res) => {
        const pageMap = {
          0: '/pages/publish/dynamic',  
          1: '/pages/publish/event',    
          2: '/pages/publish/work'      
        };

        if (pageMap[res.tapIndex]) {
          console.log("跳转到：", pageMap[res.tapIndex]);
          wx.navigateTo({ url: pageMap[res.tapIndex] });
        }
      },
      fail: (res) => {
        console.log("操作取消", res.errMsg);
      }
    });
  },

  // 收藏按钮点击
  handleCollect: function (e) {
    // 不需要stopPropagation，因为使用了catchtap
    const index = e.currentTarget.dataset.index;
    const card = this.data.cardList[index];
    const isCollected = !card.isCollected;
    
    // 更新收藏状态和数量
    this.setData({
      [`cardList[${index}].isCollected`]: isCollected,
      [`cardList[${index}].collectCount`]: isCollected ? card.collectCount + 1 : Math.max(0, card.collectCount - 1)
    });
    
    wx.showToast({
      title: isCollected ? '已收藏' : '已取消收藏',
      icon: 'success'
    });
  },

  // 分享按钮点击
  handleShare: function (e) {
    // 不需要stopPropagation，因为使用了catchtap
    const index = e.currentTarget.dataset.index;
    const card = this.data.cardList[index];
    
    // 更新分享数量
    this.setData({
      [`cardList[${index}].shareCount`]: card.shareCount + 1
    });
    
    // 设置分享参数
    this.shareData = {
      index: index,
      title: card.title,
      path: `/pages/detail/detail?id=${card.id}`
    };
    
    // 显示系统分享菜单
    wx.showShareMenu({
      withShareTicket: true,
      menus: ['shareAppMessage', 'shareTimeline']
    });
  },

  // 评论按钮点击
  handleComment: function (e) {
    // 不需要stopPropagation，因为使用了catchtap
    const index = e.currentTarget.dataset.index;
    const card = this.data.cardList[index];
    
    // 模拟获取评论数据
    const commentList = this.getCommentList(card.id);
    
    this.setData({
      currentCardIndex: index,
      commentList: commentList,
      commentText: '',
      showCommentPopup: true,
      inputFocus: true  // 自动聚焦输入框
    });
    
    // 滚动到最新评论
    if (commentList.length > 0) {
      this.setData({
        scrollIntoView: 'comment-' + commentList[commentList.length - 1].id
      });
    }
  },
  
  // 获取评论列表（模拟数据）
  getCommentList: function(cardId) {
    // 这里应该是从服务器获取评论数据的逻辑
    // 现在使用模拟数据
    if (cardId === 1) {
      return [
        {
          id: 1,
          userid: 'user001',
          username: '小明',
          avatar: 'https://objectstorageapi.bja.sealos.run/a0qepsyj-001/text/Default%20avatar/d907281-0.png',
          content: '这个分享很有价值，我学到了很多新的编程技巧，特别是关于小程序框架的使用方法。希望能有更多这样的内容分享！',
          time: '2小时前',
          likeCount: 5,
          isLiked: false,
          expanded: false
        },
        {
          id: 2,
          userid: 'user002',
          username: '小红',
          avatar: 'https://objectstorageapi.bja.sealos.run/a0qepsyj-001/text/Default%20avatar/d907281-1.png',
          content: '学到了很多，谢谢分享',
          time: '1小时前',
          likeCount: 2,
          isLiked: false,
          expanded: false,
          isReply: true,
          replyTo: '小明'
        }
      ];
    } else if (cardId === 2) {
      return [
        {
          id: 3,
          userid: 'user003',
          username: '小华',
          avatar: 'https://objectstorageapi.bja.sealos.run/a0qepsyj-001/text/Default%20avatar/d928162-0.png',
          content: '加油！继续坚持学习！',
          time: '3小时前',
          likeCount: 1,
          isLiked: false,
          expanded: false
        }
      ];
    } else if (cardId === 4) {
      return [
        {
          id: 4,
          userid: 'user004',
          username: '小李',
          avatar: 'https://objectstorageapi.bja.sealos.run/a0qepsyj-001/text/Default%20avatar/d928162-1.png',
          content: '编程活动在哪报名？请问有链接吗？',
          time: '5小时前',
          likeCount: 0,
          isLiked: false,
          expanded: false
        },
        {
          id: 5,
          userid: 'user005',
          username: '小王',
          avatar: 'https://objectstorageapi.bja.sealos.run/a0qepsyj-001/text/Default%20avatar/d907281-0.png',
          content: '我也想参加，求详细信息',
          time: '4小时前',
          likeCount: 0,
          isLiked: false,
          expanded: false
        }
      ];
    }
    return [];
  },
  
  // 关闭评论弹窗
  closeCommentPopup: function() {
    this.setData({
      showCommentPopup: false,
      inputFocus: false
    });
  },
  
  // 阻止冒泡
  stopPropagation: function(e) {
    // 这里需要保留，用于评论弹窗的点击阻止冒泡
    e.stopPropagation();
  },
  
  // 评论输入
  onCommentInput: function(e) {
    this.setData({
      commentText: e.detail.value
    });
  },
  
  // 切换评论展开/收起状态
  toggleCommentExpand: function(e) {
    const index = e.currentTarget.dataset.index;
    this.setData({
      [`commentList[${index}].expanded`]: !this.data.commentList[index].expanded
    });
  },

  // 评论点赞
  likeComment: function(e) {
    const index = e.currentTarget.dataset.index;
    const comment = this.data.commentList[index];
    const isLiked = !comment.isLiked;
    const likeCount = isLiked ? comment.likeCount + 1 : Math.max(0, comment.likeCount - 1);
    
    this.setData({
      [`commentList[${index}].isLiked`]: isLiked,
      [`commentList[${index}].likeCount`]: likeCount
    });
    
    // 在实际应用中，应该发送请求到服务器保存点赞状态
    wx.showToast({
      title: isLiked ? '已点赞' : '已取消点赞',
      icon: 'none',
      duration: 1000
    });
  },
  
  // 回复评论
  replyComment: function(e) {
    const index = e.currentTarget.dataset.index;
    const comment = this.data.commentList[index];
    
    this.setData({
      replyTo: {
        id: comment.id,
        username: comment.username,
        userid: comment.userid
      },
      replyPlaceholder: `回复 @${comment.username}`,
      inputFocus: true
    });
  },
  
  // 头像点击 - 跳转到用户资料页
  navigateToUserProfile: function(e) {
    // 防止冒泡触发其他事件
    if (e && typeof e.stopPropagation === 'function') {
      e.stopPropagation();
    }
    
    // 获取点击的卡片索引
    const index = e.currentTarget.dataset.index;
    const cardData = this.data.cardList[index];
    
    console.log('正在跳转到用户资料页，用户:', cardData.title);
    
    wx.navigateTo({
      url: `/pages/user-profile/user-profile?userId=${cardData.id}&userName=${encodeURIComponent(cardData.title)}&userAvatar=${encodeURIComponent(cardData.avatar)}`,
      success: function() {
        console.log('跳转到用户资料页成功');
      },
      fail: function(err) {
        console.error('跳转到用户资料页失败:', err);
      }
    });
  },

  // 昵称点击 - 同样跳转到用户资料页
  navigateToUserProfileByName: function(e) {
    // 防止冒泡触发其他事件
    if (e && typeof e.stopPropagation === 'function') {
      e.stopPropagation();
    }
    
    // 获取点击的卡片索引
    const index = e.currentTarget.dataset.index;
    const cardData = this.data.cardList[index];
    
    console.log('正在跳转到用户资料页，用户:', cardData.title);
    
    wx.navigateTo({
      url: `/pages/user-profile/user-profile?userId=${cardData.id}&userName=${encodeURIComponent(cardData.title)}&userAvatar=${encodeURIComponent(cardData.avatar)}`,
      success: function() {
        console.log('跳转到用户资料页成功');
      },
      fail: function(err) {
        console.error('跳转到用户资料页失败:', err);
      }
    });
  },

  // 群聊点击 - 跳转到群聊页面
  navigateToGroupChat: function(e) {
    // 防止冒泡触发其他事件
    if (e && typeof e.stopPropagation === 'function') {
      e.stopPropagation();
    }
    
    // 获取点击的卡片索引
    const index = e.currentTarget.dataset.index;
    const cardData = this.data.cardList[index];
    
    if (!cardData.group) {
      console.warn('该卡片没有群聊信息');
      return;
    }
    
    console.log('正在跳转到群聊页面，群组:', cardData.group.name);
    
    // 跳转到群聊页面，传递群组信息
    wx.navigateTo({
      url: `/pages/chat/chat?id=${cardData.id}&name=${encodeURIComponent(cardData.group.name)}&avatar=${encodeURIComponent(cardData.group.avatar)}&type=group`,
      success: function() {
        console.log('跳转到群聊页面成功');
      },
      fail: function(err) {
        console.error('跳转到群聊页面失败:', err);
      }
    });
  },

  // 标签点击 - 跳转到标签相关内容页面
  navigateToTagContent: function(e) {
    // 防止冒泡触发其他事件
    if (e && typeof e.stopPropagation === 'function') {
      e.stopPropagation();
    }
    
    // 获取点击的标签文本
    const tagText = e.currentTarget.dataset.tag;
    
    console.log('正在跳转到标签相关内容页面，标签:', tagText);
    
    wx.navigateTo({
      url: `/pages/search/search?keyword=${encodeURIComponent(tagText)}&type=tag`,
      success: function() {
        console.log('跳转到标签内容页面成功');
      },
      fail: function(err) {
        console.error('跳转到标签内容页面失败:', err);
      }
    });
  },

  // 评论中的头像点击 - 跳转到对应用户资料页
  viewUserProfile: function(e) {
    // 防止冒泡触发其他事件
    if (e && typeof e.stopPropagation === 'function') {
      e.stopPropagation();
    }
    
    const userId = e.currentTarget.dataset.userid;
    
    // 查找评论列表中的用户信息
    let userInfo = null;
    for (const comment of this.data.commentList) {
      if (comment.userid === userId) {
        userInfo = {
          id: comment.userid,
          name: comment.username,
          avatar: comment.avatar
        };
        break;
      }
    }
    
    if (!userInfo) {
      console.warn('未找到该用户信息');
      return;
    }
    
    console.log('正在查看用户资料:', userInfo.name);
    
    wx.navigateTo({
      url: `/pages/user-profile/user-profile?userId=${userInfo.id}&userName=${encodeURIComponent(userInfo.name)}&userAvatar=${encodeURIComponent(userInfo.avatar)}`,
      success: function() {
        console.log('跳转到用户资料页成功');
      },
      fail: function(err) {
        console.error('跳转到用户资料页失败:', err);
      }
    });
  },

  // 显示评论长按菜单
  showCommentMenu: function(e) {
    const index = e.currentTarget.dataset.index;
    const comment = this.data.commentList[index];
    
    // 检查是否是自己的评论
    const userInfo = wx.getStorageSync('userInfo') || {};
    const isOwnComment = userInfo.userid === comment.userid;
    
    this.setData({
      showCommentMenu: true,
      currentCommentIndex: index,
      isOwnComment: isOwnComment
    });
  },
  
  // 隐藏评论长按菜单
  hideCommentMenu: function() {
    this.setData({
      showCommentMenu: false
    });
  },
  
  // 复制评论内容
  copyComment: function() {
    const index = this.data.currentCommentIndex;
    if(index === -1) return;
    
    const content = this.data.commentList[index].content;
    wx.setClipboardData({
      data: content,
      success: () => {
        wx.showToast({
          title: '复制成功',
          icon: 'success'
        });
        this.hideCommentMenu();
      }
    });
  },
  
  // 回复指定评论
  replyToComment: function() {
    const index = this.data.currentCommentIndex;
    if(index === -1) return;
    
    const comment = this.data.commentList[index];
    this.setData({
      replyTo: {
        id: comment.id,
        username: comment.username,
        userid: comment.userid
      },
      replyPlaceholder: `回复 @${comment.username}`,
      inputFocus: true,
      showCommentMenu: false
    });
  },
  
  // 删除评论
  deleteComment: function() {
    const index = this.data.currentCommentIndex;
    if(index === -1) return;
    
    wx.showModal({
      title: '删除评论',
      content: '确定要删除这条评论吗？',
      success: (res) => {
        if (res.confirm) {
          const commentList = [...this.data.commentList];
          commentList.splice(index, 1);
          
          // 更新评论列表和卡片评论数
          const cardIndex = this.data.currentCardIndex;
          const card = this.data.cardList[cardIndex];
          
          this.setData({
            commentList: commentList,
            [`cardList[${cardIndex}].commentCount`]: Math.max(0, card.commentCount - 1),
            showCommentMenu: false
          });
          
          wx.showToast({
            title: '删除成功',
            icon: 'success'
          });
        } else {
          this.hideCommentMenu();
        }
      }
    });
  },
  
  // 处理评论点击事件（避免与长按和子元素点击冲突）
  handleCommentTap: function(e) {
    // 空函数，避免点击冒泡
  },
  
  // 修改提交评论处理函数
  submitComment: function() {
    if (!this.data.commentText.trim()) {
      wx.showToast({
        title: '评论内容不能为空',
        icon: 'none'
      });
      return;
    }
    
    const index = this.data.currentCardIndex;
    if (index === -1) return;
    
    // 模拟提交评论
    const userInfo = wx.getStorageSync('userInfo') || {
      userid: 'currentUser',
      nickName: '我',
      avatarUrl: 'https://objectstorageapi.bja.sealos.run/a0qepsyj-001/text/Default%20avatar/d907281-0.png'
    };
    
    // 创建新评论对象
    const newComment = {
      id: new Date().getTime(),
      userid: userInfo.userid,
      username: userInfo.nickName,
      avatar: userInfo.avatarUrl,
      content: this.data.commentText,
      time: '刚刚',
      likeCount: 0,
      isLiked: false,
      expanded: false
    };
    
    // 如果是回复评论，添加回复信息
    if (this.data.replyTo) {
      newComment.isReply = true;
      newComment.replyTo = this.data.replyTo.username;
      newComment.replyToId = this.data.replyTo.id;
    }
    
    // 更新评论列表和评论数
    const commentList = [...this.data.commentList, newComment]; // 将新评论追加到列表末尾
    const card = this.data.cardList[index];
    
    this.setData({
      commentList: commentList,
      commentText: '',
      [`cardList[${index}].commentCount`]: card.commentCount + 1,
      scrollIntoView: 'comment-' + newComment.id, // 滚动到新评论
      replyTo: null,
      replyPlaceholder: ''
    });
    
    wx.showToast({
      title: '评论成功',
      icon: 'success'
    });
  },

  // 围观按钮点击
  handleWatch: function (e) {
    // 不需要stopPropagation，因为使用了catchtap
    const index = e.currentTarget.dataset.index;
    const card = this.data.cardList[index];
    const isWatched = !card.isWatched;
    
    // 更新围观状态和数量
    this.setData({
      [`cardList[${index}].isWatched`]: isWatched,
      [`cardList[${index}].watchCount`]: isWatched ? card.watchCount + 1 : Math.max(0, card.watchCount - 1)
    });
    
    wx.showToast({
      title: isWatched ? '已围观' : '已取消围观',
      icon: 'none'
    });
  },

  // 参与活动按钮点击
  handleReplay: function (e) {
    e.stopPropagation();
    wx.showModal({
      title: '参与活动',
      content: '确定要参与此活动吗？',
      success: (res) => {
        if (res.confirm) {
          wx.showToast({
            title: '参与成功',
            icon: 'success'
          });
        }
      }
    });
  },

  onLoad: function() {
    console.log('页面加载');
    // 尝试使用工具函数更新URL，但保留默认值作为备份
    try {
      const updatedBannerList = this.data.bannerList.map((item, index) => {
        return {
          ...item,
          imageUrl: getObjectURL(`miniprogram-cdn/banner${index+1}.png`) || item.imageUrl
        };
      });
      
      const updatedCardList = this.data.cardList.map((item, index) => {
        return {
          ...item,
          avatar: getDefaultAvatarURL(index % 4) || item.avatar
        };
      });
      
      this.setData({
        bannerList: updatedBannerList,
        cardList: updatedCardList
      });
      
      console.log('成功更新图片URL');
    } catch (error) {
      console.error('更新图片URL失败:', error);
    }
  },

  onPullDownRefresh: function () {
    setTimeout(() => {
      wx.stopPullDownRefresh();
      wx.showToast({
        title: '刷新成功',
        icon: 'success'
      });
    }, 1000);
  },

  onShow: function() {
    // 设置当前页面对应的tabBar索引
    if (typeof this.getTabBar === 'function' && this.getTabBar()) {
      this.getTabBar().setData({
        selected: 0
      });
    }
    
    // 更新全局变量
    const app = getApp();
    if (app.globalData) {
      app.globalData.tabBarIndex = 0;
    }
  },

  onShareAppMessage: function (res) {
    // 来自页面内分享按钮
    if (res.from === 'button') {
      const index = res.target.dataset.index;
      const card = this.data.cardList[index];
      return {
        title: card.title,
        path: `/pages/detail/detail?id=${card.id}`,
        imageUrl: card.imageUrl || ''
      };
    }
    
    // 使用shareData，如果存在
    if (this.shareData) {
      const result = {
        title: this.shareData.title,
        path: this.shareData.path
      };
      // 用完后清空
      this.shareData = null;
      return result;
    }
    
    // 默认分享
    return {
      title: '在校生求职社交平台',
      path: '/pages/home/home'
    };
  },
  
  onShareTimeline: function() {
    return {
      title: '在校生求职社交平台',
      query: ''
    };
  }
});
